package com.angel.core.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

import com.angel.core.Constants;
import com.github.pagehelper.StringUtil;

/**
 * @author cheng sir
 * 2016年9月7日下午5:31:10
 */
public class FileUpload {

	/**
	 * 文件上传到本地
	 * @param multiFileMap
	 * @return
	 * @throws IOException
	 */
	public static int upload(MultiValueMap<String , MultipartFile> multiFileMap,String file) throws IOException{
		List<Object> uploadList = new ArrayList<Object>();
		Iterator<String> iterator = multiFileMap.keySet().iterator();
		if(iterator.hasNext()) {
			String key = iterator.next();
			List<MultipartFile> list = multiFileMap.get(key);
			for(MultipartFile multipartFile : list) {
				String originalFilename = multipartFile.getOriginalFilename();
				if(StringUtils.isEmpty(originalFilename)){
					continue;
				}
//				if(StringUtils.endsWith(originalFilename , "png") || StringUtils.endsWith(originalFilename , "jpg") || StringUtils.endsWith(originalFilename , "jpeg") || StringUtils.endsWith(originalFilename , "bmp") || StringUtils.endsWith(originalFilename , "png")) {
					String suffix = StringUtils.substringAfterLast(originalFilename , ".");
					File files = new File(file,UUID.randomUUID().toString().replace("-" , "") +"." + suffix);
					
					FileUtils.copyInputStreamToFile(multipartFile.getInputStream() , files);
					uploadList.add(originalFilename);
//				} else {
//					return 0;
//				}
			}
		}
		return uploadList.size();
	}
	
	/**
	 * fastdfs上传
	 * @param multiFileMap
	 * @return
	 * @throws Exception
	 */
	public static String uploadForFastdfs(MultiValueMap<String , MultipartFile> multiFileMap) throws Exception{
		String urls = "";
		Iterator<String> iterator = multiFileMap.keySet().iterator();
		String fasedfs_url = PropertyConfUtil.getContextProperty(Constants.FASTDFS_UTL);
		while(iterator.hasNext()) {
			String key = iterator.next();
			List<MultipartFile> list = multiFileMap.get(key);
			for(MultipartFile multipartFile : list) {
				String originalFilename = multipartFile.getOriginalFilename();
				if(StringUtils.isEmpty(originalFilename)){
					continue;
				}
				FastDFSClient client = new FastDFSClient();
				String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
				String path = client.uploadFile(multipartFile.getBytes(), extName);
				String uploadUrl = fasedfs_url + path;
				urls += uploadUrl+",";
			}
		}
		if(!StringUtil.isEmpty(urls)){
			urls = urls.substring(0,urls.length()-1);
		}
		return urls;
	}
	
}
